<template>
  <el-dialog v-model="dialogVisible" :title="'添加'" width="40%" @close="dialogVisible = false">
    <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
      <!-- <el-form-item label="会员姓名" prop="username">
        <el-input v-model="form.username" :readonly="true" class="!w-240px" />
      </el-form-item> -->
      <el-form-item label="会员手机号码" prop="mobile">
        <el-input v-model="form.mobile" :readonly="true" class="!w-240px" />
      </el-form-item>
      <el-form-item label="计费方式" prop="purchaseType">
        <el-radio-group v-model="form.purchaseType">
          <el-radio
v-for="item in getDictOptions(DICT_TYPE.TONGUE_BILLING_METHOD)"  :key="item.value"  :disabled="!purchase.some(p => p.type === item.value)"
            :value="item.value" :label="item.label"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="添加次数" prop="addTimes">
        <el-input-number
          :disabled="form.purchaseType!=='TIMES'"
v-model.trim="form.addTimes" placeholder="请输入添加次数" class="!w-240px" :min="1" :max="100000"
          :controls="false" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { TongueMemberApi } from '@/api/application/tongue/member'
import { TongueBasicApi } from '@/api/application/tongue/basic'

const dialogVisible = ref(false)
const purchase = ref([])
const open = async (data?: any) => {
  dialogVisible.value = true
  resetForm()
  form.value = {
    userId: data.id,
    mobile: data.mobile,
    purchaseType: data.purchaseType || '',
    addTimes: 0
  }
}
defineExpose({ open })
const emits = defineEmits<{
  (emitStr: 'success'): void
}>()
const form = ref({
  userId: 0,
  mobile: '',
  purchaseType: '',
  addTimes: 0
})
const rules = ref({
  purchaseType: [{ required: true, message: '请选择计费方式', trigger: 'change' }],
  // 舌诊额度：手动输入，必须是整数，最大输入 100000 
  addTimes: [
    {
      required: true,
      message: '请输入添加次数',
      trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error('请输入添加次数'))
        }
        callback()
      }
    }],
})
const formRef = ref()
watch(
  () => form.value.purchaseType,
  (newVal) => {
    if (newVal !== 'TIMES') {
      const matchedPurchase = purchase.value.find(item => item.type === newVal);
      if (matchedPurchase) {
        form.value.addTimes = matchedPurchase.count;
      } 
    }else {
        form.value.addTimes = 1;
      }
  },
  { immediate: true } // 可选：立即执行一次
);
const handleSave = async () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const obj = {
        ...form.value,
        channel:3,
      }
      TongueMemberApi.setMemberTimes(obj).then((res: any) => {
        emits('success')
      }).finally(() => {
        dialogVisible.value = false
      })
    } else {
      return false
    }
  })
}
/** 重置表单 */
const resetForm = () => {
  formRef.value?.resetFields()
}
onMounted(() =>{
  TongueBasicApi.getTongueBasice().then((res) => {
    if(res){
      const arr = res.purchaseConfig && JSON.parse(res.purchaseConfig)
      purchase.value = arr
    }
  })
})
</script>

<style scoped lang="scss"></style>